// pages/feedback/feedback.js
const app = getApp();
const baseUrl = app.getApiBaseUrl();

Page({
  data: {
    description: "",
    imagePath: "",
    contact: "",
    uploadLog: false, // 默认不上传日志
    categoryList: ["使用困难", "意见或建议", "合作", "其他"], // 反馈种类选项
    categoryIndex: 0, // 默认选中第一个
    category: "使用困难" // 默认值
  },

  bindDescriptionInput(e) {
    this.setData({ 
      description: e.detail.value 
    });
  },

  bindContactInput(e) {
    this.setData({ 
      contact: e.detail.value 
    });
  },

  bindCategoryChange(e) {
    const index = e.detail.value;
    this.setData({
      categoryIndex: index,
      category: this.data.categoryList[index]
    });
  },

  chooseImage() {
    wx.chooseImage({
      count: 1,
      success: res => {
        this.setData({ imagePath: res.tempFilePaths[0] });
      },
      fail: err => {
        wx.showToast({ title: "选择图片失败", icon: "none" });
        console.error("选择图片失败:", err);
      }
    });
  },

  deleteImage() {
    this.setData({ imagePath: "" });
  },

  toggleLogUpload(e) {
    this.setData({ uploadLog: e.detail.value });
  },

  submitFeedback() {
    const { description, imagePath, contact, uploadLog, category } = this.data;
  
    if (!description || description.length < 10) {
      wx.showToast({ title: "问题描述需至少10字", icon: "none" });
      return;
    }
    
    // 检查联系方式（如果输入了）
    if (contact) {
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!phoneRegex.test(contact)) {
        wx.showToast({ title: "请输入有效的手机号", icon: "none" });
        return;
      }
    }
  
    const openID = wx.getStorageSync('openID');
    if (!openID) {
      wx.showToast({ title: "用户身份未获取，请重试", icon: "none" });
      return;
    }
  
    const apiUrl = `${baseUrl}/feedback/submit`;
    const formData = {
      openID: openID,
      category: category,
      description: description,
      contact: contact,
      uploadLog: uploadLog ? "true" : "false"
    };
    console.log("发送的 formData:", formData);
  
    if (imagePath) {
      wx.uploadFile({
        url: apiUrl,
        filePath: imagePath,
        name: 'screenshot',
        formData: formData,
        success: res => {
          const data = JSON.parse(res.data);
          if (data.feedbackID) {
            wx.showToast({ title: "感谢反馈，我们会尽快处理", icon: "success" });
            this.setData({ 
              description: "", 
              imagePath: "", 
              contact: "", 
              uploadLog: false,
              categoryIndex: 0,
              category: "使用困难"
            });
          } else {
            wx.showToast({ title: "提交失败：" + (data.detail || '未知错误'), icon: "none" });
            console.error("提交失败:", data);
          }
        },
        fail: err => {
          wx.showToast({ title: "提交失败，请稍后重试", icon: "none" });
          console.error("提交失败:", err);
        }
      });
    } else {
      wx.request({
        url: apiUrl,
        method: 'POST',
        data: formData,
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        success: res => {
          if (res.data.feedbackID) {
            wx.showToast({ title: "感谢反馈，我们会尽快处理", icon: "success" });
            this.setData({ 
              description: "", 
              imagePath: "", 
              contact: "", 
              uploadLog: false,
              categoryIndex: 0,
              category: "使用困难"
            });
          } else {
            wx.showToast({ title: "提交失败：" + (res.data.detail || '未知错误'), icon: "none" });
            console.error("提交失败:", res.data);
          }
        },
        fail: err => {
          wx.showToast({ title: "提交失败，请稍后重试", icon: "none" });
          console.error("提交失败:", err);
        }
      });
    }
  },

  previewQRCode() {
    wx.previewImage({
      urls: ["/images/wechat_qr_code.jpg"]
    });
  }
});